function getRandomStr(expect = 5) {
  let str = Math.random().toString(36).substring(2);
  while (str.length < expect) {
    str = Math.random().toString(36).substring(2);
  }
  return str.substring(0, expect);
}
const delay = () => {
  return new Promise((resolve) => {
    let timer: any = window.setTimeout(() => {
      window.clearTimeout(timer);
      timer = null;
      resolve({});
    }, 1000);
  });
};
const loadVideo = (videoUrl: String) => {
  return new Promise((resolve) => {
    const videoDom: any = document.createElement("video");
    const videoId = `videoPoster_${getRandomStr()}`;
    videoDom.style.position = "absolute";
    videoDom.style.zIndex = "-9999";
    videoDom.style.top = "-9999px";
    videoDom.setAttribute("id", videoId);
    videoDom.setAttribute("preload", "auto");
    videoDom.src = videoUrl;
    videoDom.addEventListener("loadeddata", () => {
      const videoInfo = {
        videoId: videoId,
        videoDom: videoDom,
        width: videoDom.videoWidth,
        height: videoDom.videoHeight,
      };
      resolve(videoInfo);
    });
    document.body.appendChild(videoDom);
  });
};
const loadVideoData = (videoUrl: String) => {
  return Promise.race([loadVideo(videoUrl), delay()]);
};
const getVideoPoster = async (file: any) => {
  //创建一个DOMString,其中包含一个表示参数中给出的对象的URL
  const videoUrl = window.URL.createObjectURL(file);
  if (!videoUrl) {
    window.console.error("请传入合法的视频链接");
    return "";
  }
  const obj: any = await loadVideoData(videoUrl);
  const { videoDom, width, height } = obj;
  if (!videoDom) {
    return "";
  }
  const canvas = document.createElement("canvas");
  canvas.height = height;
  canvas.width = width;
  const ctx = canvas.getContext("2d");
  ctx?.drawImage(videoDom, 0, 0, canvas.width, canvas.height);
  document.body.removeChild(videoDom);
  return {
    poster: canvas.toDataURL("image/png"),
    width,
    height,
    rate: width / height,
  };
};
